Popular Searches
Popular Course Categories
Popular Courses

Introduction to Inheritance in Java

Introduction to Inheritance in Java

Encapsulation, Inheritance, and Polymorphism

<div class="core-java-notes">

<h1>Introduction to Inheritance in Java</h1>

<p><strong>Course:</strong> Core Java Training</p>

<p><strong>Topic:</strong> Introduction to Inheritance in Java</p>

<p><strong>Course Link:</strong> <a href="https://www.justacademy.co/course-detail/core-java-training" target="_blank" rel="noopener noreferrer">Core Java Training Course</a></p>

<p><strong>Demo Link:</strong> <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for a Course Demo</a></p>

<p><strong>Website:</strong> <a href="https://www.justacademy.co/" target="_blank" rel="noopener noreferrer">JustAcademy</a></p>

<hr>

<h2>1. Introduction to Inheritance</h2>

<p>Inheritance is one of the fundamental concepts of object-oriented programming (OOP) in Java. It allows one class to acquire accessible fields and methods from another class. Instead of writing the same functionality repeatedly, developers can define common behavior in a parent class and extend it in child classes.</p>

<p>For example, a general <code>Vehicle</code> class may contain common properties such as brand and speed, along with methods such as <code>start()</code> and <code>stop()</code>. Classes such as <code>Car</code>, <code>Bike</code>, and <code>Truck</code> can extend <code>Vehicle</code> and add their own specialized properties and behavior.</p>

<p>Inheritance promotes code reuse, reduces duplication, supports method overriding, and helps establish relationships between related classes. <a href="https://dev.java/learn/inheritance/what-is-inheritance/" target="_blank" rel="noopener noreferrer">Java's inheritance documentation</a> explains how subclasses build upon existing classes.</p>

<h2>2. Learning Objectives</h2>

<ul>

<li>Understand the meaning and purpose of inheritance in Java.</li>

<li>Learn the roles of parent classes and child classes.</li>

<li>Understand the <code>extends</code> keyword and inheritance syntax.</li>

<li>Learn how inherited methods and accessible fields can be reused.</li>

<li>Explore the major forms of class inheritance.</li>

<li>Understand constructors and the <code>super</code> keyword in inheritance.</li>

<li>Learn method overriding and its relationship to polymorphism.</li>

<li>Identify the limitations and best practices of inheritance.</li>

</ul>

<h2>3. What Is Inheritance in Java?</h2>

<p>Inheritance is a mechanism through which a class derives from another class. The derived class can reuse accessible behavior from the existing class and define additional features of its own.</p>

<p>Java uses the <code>extends</code> keyword to establish inheritance between classes.</p>

<h3>Important Terminology</h3>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Term</th><th>Meaning</th></tr>

<tr><td>Superclass</td><td>The parent or base class from which another class derives.</td></tr>

<tr><td>Subclass</td><td>The child or derived class that extends another class.</td></tr>

<tr><td>Inheritance</td><td>The mechanism that allows a subclass to reuse accessible members and specialize behavior.</td></tr>

<tr><td><code>extends</code></td><td>The keyword used to declare that a class inherits from another class.</td></tr>

<tr><td><code>super</code></td><td>A keyword used to refer to superclass members or invoke a superclass constructor.</td></tr>

<tr><td>Method overriding</td><td>A subclass provides a compatible implementation of an inherited instance method.</td></tr>

<tr><td>Code reusability</td><td>The ability to use existing functionality without unnecessarily rewriting it.</td></tr>

</table>

<h2>4. Basic Syntax of Inheritance</h2>

<p>The general syntax for creating a subclass is:</p>

<pre><code>class ParentClass {

    // Common fields and methods

}

 

class ChildClass extends ParentClass {

    // Additional fields and methods

}</code></pre>

<p>In this structure, <code>ChildClass</code> extends <code>ParentClass</code>. The child class can use accessible inherited members and add new fields and methods.</p>

<h2>5. First Inheritance Example</h2>

<p>Consider a program in which an <code>Animal</code> class defines a common method and a <code>Dog</code> class inherits that method.</p>

<pre><code>class Animal {

    void eat() {

        System.out.println("Animal is eating");

    }

}

 

class Dog extends Animal {

    void bark() {

        System.out.println("Dog is barking");

    }

}

 

public class InheritanceDemo {

    public static void main(String[] args) {

        Dog dog = new Dog();

 

        dog.eat();

        dog.bark();

    }

}</code></pre>

<h3>Output</h3>

<pre><code>Animal is eating

Dog is barking</code></pre>

<h3>Explanation</h3>

<ul>

<li><code>Animal</code> is the superclass.</li>

<li><code>Dog</code> is the subclass because it extends <code>Animal</code>.</li>

<li>The <code>eat()</code> method is inherited from <code>Animal</code>.</li>

<li>The <code>bark()</code> method is defined directly in <code>Dog</code>.</li>

<li>The <code>Dog</code> object can call both methods because they are accessible.</li>

</ul>

<h2>6. Why Is Inheritance Used?</h2>

<p>Inheritance is useful when multiple classes share common characteristics but also need specialized behavior.</p>

<ul>

<li><strong>Code reuse:</strong> Common fields and methods can be defined once in a superclass.</li>

<li><strong>Reduced duplication:</strong> Similar classes do not need to repeat the same implementation.</li>

<li><strong>Extensibility:</strong> Subclasses can add specialized fields and methods.</li>

<li><strong>Maintainability:</strong> Shared behavior can be updated centrally when the class design supports it.</li>

<li><strong>Polymorphism:</strong> Subclass objects can be used through suitable superclass references.</li>

<li><strong>Logical relationships:</strong> Inheritance models an appropriate “is-a” relationship between types.</li>

</ul>

<h2>7. Understanding the Parent Class</h2>

<p>A parent class contains the common fields and methods that related subclasses can reuse. It provides the shared foundation for the class hierarchy.</p>

<h3>Example</h3>

<pre><code>class Vehicle {

    String brand;

    int speed;

 

    void start() {

        System.out.println("Vehicle is starting");

    }

 

    void stop() {

        System.out.println("Vehicle is stopping");

    }

}</code></pre>

<p>The <code>Vehicle</code> class defines two fields and two methods. Different vehicle subclasses can inherit these features instead of implementing them independently.</p>

<h2>8. Understanding the Child Class</h2>

<p>A child class extends a parent class and can add its own properties and behavior. It can also override eligible inherited instance methods to provide specialized implementations.</p>

<h3>Example</h3>

<pre><code>class Car extends Vehicle {

    int numberOfDoors;

 

    void playMusic() {

        System.out.println("Car music system is playing");

    }

}</code></pre>

<p>The <code>Car</code> class inherits the accessible members of <code>Vehicle</code> and adds the <code>numberOfDoors</code> field and <code>playMusic()</code> method.</p>

<h2>9. Complete Example: Vehicle Inheritance</h2>

<pre><code>class Vehicle {

    String brand;

    int speed;

 

    void start() {

        System.out.println(brand + " is starting");

    }

 

    void displaySpeed() {

        System.out.println("Speed: " + speed + " km/h");

    }

}

 

class Car extends Vehicle {

    int numberOfDoors;

 

    void displayCarDetails() {

        System.out.println("Brand: " + brand);

        System.out.println("Doors: " + numberOfDoors);

    }

}

 

public class VehicleDemo {

    public static void main(String[] args) {

        Car car = new Car();

 

        car.brand = "Toyota";

        car.speed = 80;

        car.numberOfDoors = 4;

 

        car.start();

        car.displaySpeed();

        car.displayCarDetails();

    }

}</code></pre>

<h3>Output</h3>

<pre><code>Toyota is starting

Speed: 80 km/h

Brand: Toyota

Doors: 4</code></pre>

<p><strong>Explanation:</strong> The <code>Car</code> object can use the accessible <code>brand</code> and <code>speed</code> fields and the <code>start()</code> and <code>displaySpeed()</code> methods inherited from <code>Vehicle</code>. It also uses its own <code>numberOfDoors</code> field and <code>displayCarDetails()</code> method.</p>

<h2>10. Types of Inheritance in Java</h2>

<p>Inheritance structures are commonly described using five patterns: single, multilevel, hierarchical, multiple, and hybrid inheritance. Java supports single, multilevel, and hierarchical inheritance through classes. Multiple inheritance of classes is not supported, but Java allows a class to implement multiple interfaces.</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Type</th><th>Description</th><th>Class Support in Java</th></tr>

<tr><td>Single inheritance</td><td>One child class extends one parent class.</td><td>Supported</td></tr>

<tr><td>Multilevel inheritance</td><td>A class extends a class that already extends another class.</td><td>Supported</td></tr>

<tr><td>Hierarchical inheritance</td><td>Multiple child classes extend the same parent class.</td><td>Supported</td></tr>

<tr><td>Multiple inheritance</td><td>One class inherits from multiple classes.</td><td>Not supported for classes; multiple interfaces can be implemented.</td></tr>

<tr><td>Hybrid inheritance</td><td>A combination of inheritance patterns.</td><td>Possible through supported class inheritance and interfaces, but not through multiple class inheritance.</td></tr>

</table>

<h2>11. Single Inheritance</h2>

<p>Single inheritance occurs when one subclass extends one superclass. It is the simplest form of class inheritance in Java.</p>

<h3>Structure</h3>

<pre><code>Animal

   |

   v

  Dog</code></pre>

<h3>Example</h3>

<pre><code>class Animal {

    void eat() {

        System.out.println("Animal eats food");

    }

}

 

class Dog extends Animal {

    void bark() {

        System.out.println("Dog barks");

    }

}

 

public class SingleInheritanceDemo {

    public static void main(String[] args) {

        Dog dog = new Dog();

 

        dog.eat();

        dog.bark();

    }

}</code></pre>

<h3>Output</h3>

<pre><code>Animal eats food

Dog barks</code></pre>

<p><strong>Explanation:</strong> The <code>Dog</code> class directly extends <code>Animal</code>. It inherits the accessible <code>eat()</code> method and defines its own <code>bark()</code> method.</p>

<h2>12. Multilevel Inheritance</h2>

<p>Multilevel inheritance occurs when a class extends a subclass, creating a chain of inheritance across multiple levels.</p>

<h3>Structure</h3>

<pre><code>Animal

   |

   v

  Dog

   |

   v

Puppy</code></pre>

<h3>Example</h3>

<pre><code>class Animal {

    void eat() {

        System.out.println("Animal eats");

    }

}

 

class Dog extends Animal {

    void bark() {

        System.out.println("Dog barks");

    }

}

 

class Puppy extends Dog {

    void weep() {

        System.out.println("Puppy weeps");

    }

}

 

public class MultilevelDemo {

    public static void main(String[] args) {

        Puppy puppy = new Puppy();

 

        puppy.eat();

        puppy.bark();

        puppy.weep();

    }

}</code></pre>

<h3>Output</h3>

<pre><code>Animal eats

Dog barks

Puppy weeps</code></pre>

<p><strong>Explanation:</strong> <code>Puppy</code> extends <code>Dog</code>, and <code>Dog</code> extends <code>Animal</code>. The puppy can use accessible methods declared at all levels of the inheritance chain.</p>

<h2>13. Hierarchical Inheritance</h2>

<p>Hierarchical inheritance occurs when multiple subclasses extend the same superclass. Each child class can reuse common behavior while adding its own specialized functionality.</p>

<h3>Structure</h3>

<pre><code>        Vehicle

        /     \

       v       v

      Car     Bike</code></pre>

<h3>Example</h3>

<pre><code>class Vehicle {

    void start() {

        System.out.println("Vehicle starts");

    }

}

 

class Car extends Vehicle {

    void drive() {

        System.out.println("Car is driving");

    }

}

 

class Bike extends Vehicle {

    void ride() {

        System.out.println("Bike is being ridden");

    }

}

 

public class HierarchicalDemo {

    public static void main(String[] args) {

        Car car = new Car();

        Bike bike = new Bike();

 

        car.start();

        car.drive();

 

        bike.start();

        bike.ride();

    }

}</code></pre>

<h3>Output</h3>

<pre><code>Vehicle starts

Car is driving

Vehicle starts

Bike is being ridden</code></pre>

<p><strong>Explanation:</strong> Both <code>Car</code> and <code>Bike</code> inherit the <code>start()</code> method from <code>Vehicle</code>. Each subclass provides a separate method for its specialized behavior.</p>

<h2>14. Multiple Inheritance and Interfaces</h2>

<p>Java does not allow a class to extend two or more classes directly. For example, the declaration <code>class C extends A, B</code> is invalid Java syntax.</p>

<p>Java supports a class implementing multiple interfaces. This allows a class to provide behavior for several type contracts without inheriting implementation from multiple classes.</p>

<h3>Example</h3>

<pre><code>interface Printable {

    void print();

}

 

interface Showable {

    void show();

}

 

class Report implements Printable, Showable {

    public void print() {

        System.out.println("Printing report");

    }

 

    public void show() {

        System.out.println("Displaying report");

    }

}

 

public class InterfaceInheritanceDemo {

    public static void main(String[] args) {

        Report report = new Report();

 

        report.print();

        report.show();

    }

}</code></pre>

<h3>Output</h3>

<pre><code>Printing report

Displaying report</code></pre>

<p><strong>Explanation:</strong> The <code>Report</code> class implements both <code>Printable</code> and <code>Showable</code>. It supplies implementations of both interface methods.</p>

<h2>15. Hybrid Inheritance</h2>

<p>Hybrid inheritance combines two or more inheritance patterns. Java cannot create hybrid inheritance by extending multiple classes, but class inheritance can be combined with multiple interfaces.</p>

<h3>Example</h3>

<pre><code>class Device {

    void powerOn() {

        System.out.println("Device powered on");

    }

}

 

interface Camera {

    void takePhoto();

}

 

interface MusicPlayer {

    void playMusic();

}

 

class Smartphone extends Device implements Camera, MusicPlayer {

    public void takePhoto() {

        System.out.println("Photo captured");

    }

 

    public void playMusic() {

        System.out.println("Music playing");

    }

}

 

public class HybridDemo {

    public static void main(String[] args) {

        Smartphone phone = new Smartphone();

 

        phone.powerOn();

        phone.takePhoto();

        phone.playMusic();

    }

}</code></pre>

<h3>Output</h3>

<pre><code>Device powered on

Photo captured

Music playing</code></pre>

<p><strong>Explanation:</strong> <code>Smartphone</code> extends one class, <code>Device</code>, and implements two interfaces. This combines class inheritance with multiple interface contracts.</p>

<h2>16. The super Keyword in Java</h2>

<p>The <code>super</code> keyword is used in a subclass to refer to its immediate superclass. It is commonly used to invoke a superclass constructor or access an accessible superclass method or field that is hidden by a subclass member.</p>

<h3>Uses of super</h3>

<ul>

<li>Call a superclass constructor using <code>super()</code> or <code>super(arguments)</code>.</li>

<li>Call an accessible superclass method using <code>super.methodName()</code>.</li>

<li>Refer to an accessible superclass field using <code>super.fieldName</code> when a subclass field hides it.</li>

</ul>

<h3>Example: Calling a Parent Constructor</h3>

<pre><code>class Person {

    String name;

 

    Person(String name) {

        this.name = name;

        System.out.println("Person constructor executed");

    }

}

 

class Student extends Person {

    int rollNumber;

 

    Student(String name, int rollNumber) {

        super(name);

        this.rollNumber = rollNumber;

        System.out.println("Student constructor executed");

    }

 

    void display() {

        System.out.println("Name: " + name);

        System.out.println("Roll Number: " + rollNumber);

    }

}

 

public class SuperDemo {

    public static void main(String[] args) {

        Student student = new Student("Meera", 101);

        student.display();

    }

}</code></pre>

<h3>Output</h3>

<pre><code>Person constructor executed

Student constructor executed

Name: Meera

Roll Number: 101</code></pre>

<p><strong>Explanation:</strong> The <code>Student</code> constructor calls <code>super(name)</code> to initialize the inherited name field through the <code>Person</code> constructor. The student-specific roll number is then initialized.</p>

<h2>17. Constructor Behavior in Inheritance</h2>

<p>Constructors are not inherited by subclasses. However, a subclass constructor can invoke a superclass constructor using <code>super()</code> or <code>super(arguments)</code>.</p>

<ul>

<li>If a constructor does not explicitly invoke another constructor, Java ordinarily inserts an implicit no-argument superclass constructor invocation when permitted.</li>

<li>If the superclass has no accessible no-argument constructor, the subclass must explicitly invoke an appropriate superclass constructor.</li>

<li>The superclass constructor chain executes before the subclass completes its own instance initialization and constructor body.</li>

<li>A constructor invocation using <code>this()</code> or <code>super()</code> must follow Java's constructor-invocation rules.</li>

</ul>

<h2>18. Method Overriding in Inheritance</h2>

<p>Method overriding occurs when a subclass provides a compatible implementation of an inherited instance method. The subclass method must have an appropriate signature and must not reduce the visibility of the overridden method.</p>

<p>Overriding allows a subclass to customize inherited behavior. The <code>@Override</code> annotation is recommended because the compiler checks that the method actually overrides or implements a compatible method.</p>

<h3>Example</h3>

<pre><code>class Animal {

    void sound() {

        System.out.println("Animal makes a sound");

    }

}

 

class Dog extends Animal {

    @Override

    void sound() {

        System.out.println("Dog barks");

    }

}

 

public class OverridingDemo {

    public static void main(String[] args) {

        Animal animal = new Animal();

        Dog dog = new Dog();

 

        animal.sound();

        dog.sound();

    }

}</code></pre>

<h3>Output</h3>

<pre><code>Animal makes a sound

Dog barks</code></pre>

<p><strong>Explanation:</strong> The <code>Dog</code> class overrides the inherited <code>sound()</code> method to provide behavior specific to dogs.</p>

<h2>19. Inheritance and Polymorphism</h2>

<p>Polymorphism allows a superclass reference to refer to an object of a subclass. When an overridden instance method is called through that reference, Java selects the implementation based on the actual object's runtime class.</p>

<h3>Example</h3>

<pre><code>class Animal {

    void sound() {

        System.out.println("Animal sound");

    }

}

 

class Cat extends Animal {

    @Override

    void sound() {

        System.out.println("Cat meows");

    }

}

 

class Dog extends Animal {

    @Override

    void sound() {

        System.out.println("Dog barks");

    }

}

 

public class PolymorphismDemo {

    public static void main(String[] args) {

        Animal animal1 = new Cat();

        Animal animal2 = new Dog();

 

        animal1.sound();

        animal2.sound();

    }

}</code></pre>

<h3>Output</h3>

<pre><code>Cat meows

Dog barks</code></pre>

<p><strong>Explanation:</strong> Both variables are declared as <code>Animal</code> references, but they point to different subclass objects. Java calls the overridden method belonging to each object's runtime class.</p>

<h2>20. Access Modifiers and Inheritance</h2>

<p>Access modifiers determine which superclass members a subclass can access. Inheritance does not make every field or method directly accessible.</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Access Level</th><th>Access by Subclass in Same Package</th><th>Access by Subclass in Another Package</th></tr>

<tr><td><code>public</code></td><td>Yes</td><td>Yes, if the declaring type is accessible</td></tr>

<tr><td><code>protected</code></td><td>Yes</td><td>Yes, subject to protected-access rules</td></tr>

<tr><td>Package-private</td><td>Yes</td><td>No direct access solely by inheritance</td></tr>

<tr><td><code>private</code></td><td>No direct access</td><td>No direct access</td></tr>

</table>

<p>A subclass does not directly inherit or access private superclass fields and methods as ordinary inherited members. It can use public or protected superclass methods that provide controlled access to private state.</p>

<h2>21. The Object Class in Java</h2>

<p><code>Object</code>, from the <code>java.lang</code> package, is the root superclass of Java classes. A class that does not explicitly extend another class implicitly extends <code>Object</code>.</p>

<p>The <code>Object</code> class provides commonly used methods such as:</p>

<ul>

<li><code>toString()</code> — returns a string representation of an object.</li>

<li><code>equals(Object obj)</code> — compares objects according to the method's implementation.</li>

<li><code>hashCode()</code> — returns a hash code value.</li>

<li><code>getClass()</code> — returns the runtime class of an object.</li>

<li><code>wait()</code>, <code>notify()</code>, and <code>notifyAll()</code> — support thread coordination when used according to their synchronization requirements.</li>

</ul>

<h2>22. Advantages of Inheritance</h2>

<ul>

<li><strong>Reusability:</strong> Common functionality can be shared through a superclass.</li>

<li><strong>Reduced duplication:</strong> Shared code does not need to be rewritten in every subclass.</li>

<li><strong>Extensibility:</strong> New subclasses can add specialized features.</li>

<li><strong>Polymorphism:</strong> Related objects can be handled through a common superclass type.</li>

<li><strong>Maintainability:</strong> Shared behavior can be maintained centrally when the hierarchy is well designed.</li>

<li><strong>Clear type relationships:</strong> A well-designed hierarchy communicates which classes are specialized forms of another class.</li>

</ul>

<h2>23. Limitations of Inheritance</h2>

<ul>

<li><strong>Tight coupling:</strong> A subclass depends on the behavior and design of its superclass.</li>

<li><strong>Limited class inheritance:</strong> A Java class can directly extend only one class.</li>

<li><strong>Complex hierarchies:</strong> Deep inheritance chains can make behavior difficult to understand.</li>

<li><strong>Fragile base class:</strong> Changes to a superclass can unintentionally affect subclasses.</li>

<li><strong>Incorrect relationships:</strong> Inheritance is unsuitable when the relationship is not genuinely an “is-a” relationship.</li>

<li><strong>Encapsulation concerns:</strong> Exposing too many protected members can make it harder to change a superclass safely.</li>

</ul>

<h2>24. Inheritance vs. Composition</h2>

<p>Inheritance represents an “is-a” relationship, while composition represents a “has-a” relationship. Composition means that a class contains or uses an object of another class instead of deriving from it.</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Feature</th><th>Inheritance</th><th>Composition</th></tr>

<tr><td>Relationship</td><td>Is-a</td><td>Has-a</td></tr>

<tr><td>Implementation</td><td>Uses <code>extends</code> for class inheritance</td><td>Stores or uses another object</td></tr>

<tr><td>Code reuse</td><td>Reuses accessible inherited behavior</td><td>Reuses behavior by delegation to a contained object</td></tr>

<tr><td>Coupling</td><td>Can create tighter coupling to the superclass</td><td>Can provide more flexible component replacement</td></tr>

<tr><td>Example</td><td><code>Dog extends Animal</code></td><td><code>Car</code> contains an <code>Engine</code></td></tr>

</table>

<p>Use inheritance when the subclass is genuinely a specialized form of the parent class. Prefer composition when a class mainly needs to use another object's functionality.</p>

<h2>25. Common Mistakes When Using Inheritance</h2>

<ul>

<li>Using inheritance only to reuse code when the relationship is not an appropriate “is-a” relationship.</li>

<li>Assuming private superclass fields are directly accessible in a subclass.</li>

<li>Trying to extend multiple classes in one class declaration.</li>

<li>Forgetting to invoke the appropriate superclass constructor when no accessible no-argument constructor exists.</li>

<li>Overriding a method with an incompatible signature or reduced visibility.</li>

<li>Confusing method overriding with method overloading.</li>

<li>Creating unnecessarily deep inheritance hierarchies.</li>

<li>Changing superclass behavior without considering its effects on subclasses.</li>

<li>Forgetting the <code>@Override</code> annotation when overriding an inherited method.</li>

<li>Making superclass fields public when protected methods or controlled access would be more appropriate.</li>

</ul>

<h2>26. Best Practices for Inheritance</h2>

<ul>

<li>Use inheritance only when there is a clear “is-a” relationship.</li>

<li>Place common behavior in a superclass only when it is genuinely shared.</li>

<li>Keep inheritance hierarchies as simple as possible.</li>

<li>Use <code>@Override</code> to make overriding intentions explicit.</li>

<li>Keep fields private where practical and expose behavior through suitable methods.</li>

<li>Use <code>super()</code> to initialize superclass state correctly.</li>

<li>Avoid changing the expected behavior of inherited methods in surprising ways.</li>

<li>Prefer composition when the relationship is “has-a” or when components need to be replaceable.</li>

<li>Write tests for both superclass behavior and subclass-specific behavior.</li>

<li>Document important assumptions that subclasses must follow.</li>

</ul>

<h2>27. Practice Exercises</h2>

<ol>

<li>Create a class named <code>Person</code> with fields for name and age. Create a <code>Student</code> subclass with a roll number.</li>

<li>Build a <code>Vehicle</code> superclass and create <code>Car</code> and <code>Bike</code> subclasses.</li>

<li>Demonstrate single inheritance using an <code>Animal</code> and <code>Dog</code> class.</li>

<li>Demonstrate multilevel inheritance using <code>LivingThing</code>, <code>Animal</code>, and <code>Dog</code>.</li>

<li>Demonstrate hierarchical inheritance with <code>Shape</code>, <code>Circle</code>, and <code>Rectangle</code>.</li>

<li>Create a parent class with a parameterized constructor and invoke it from a child constructor using <code>super()</code>.</li>

<li>Override a superclass method in a subclass and demonstrate the use of <code>@Override</code>.</li>

<li>Use a superclass reference to call overridden methods on two different subclass objects.</li>

<li>Implement two interfaces in one class to demonstrate multiple interface implementation.</li>

<li>Create a class that contains an object of another class and compare the design with an inheritance-based approach.</li>

</ol>

<h2>28. Interview Questions and Answers</h2>

<h3>Q1. What is inheritance in Java?</h3>

<p>Inheritance is an OOP mechanism that allows a class to derive from another class, reusing accessible members and adding specialized behavior.</p>

<h3>Q2. Which keyword is used for class inheritance?</h3>

<p>The <code>extends</code> keyword is used to declare that a class extends another class.</p>

<h3>Q3. What is a superclass?</h3>

<p>A superclass is the parent or base class from which another class derives.</p>

<h3>Q4. What is a subclass?</h3>

<p>A subclass is a child or derived class that extends a superclass.</p>

<h3>Q5. Does Java support multiple inheritance through classes?</h3>

<p>No. A class can extend only one direct superclass. Java does allow a class to implement multiple interfaces.</p>

<h3>Q6. What is single inheritance?</h3>

<p>Single inheritance occurs when one subclass extends one superclass.</p>

<h3>Q7. What is multilevel inheritance?</h3>

<p>Multilevel inheritance occurs when a class extends a subclass that itself extends another class, forming an inheritance chain.</p>

<h3>Q8. What is hierarchical inheritance?</h3>

<p>Hierarchical inheritance occurs when multiple subclasses extend the same superclass.</p>

<h3>Q9. What is the purpose of the super keyword?</h3>

<p>The <code>super</code> keyword can invoke a superclass constructor or access an accessible superclass field or method.</p>

<h3>Q10. Are constructors inherited in Java?</h3>

<p>No. Constructors are not inherited, but a subclass constructor can invoke a superclass constructor.</p>

<h3>Q11. What is method overriding?</h3>

<p>Method overriding occurs when a subclass supplies a compatible implementation of an inherited instance method.</p>

<h3>Q12. What is the difference between inheritance and polymorphism?</h3>

<p>Inheritance establishes relationships between classes and allows member reuse. Polymorphism allows a common type to refer to objects of different compatible types and dispatch overridden instance methods according to the runtime object.</p>

<h3>Q13. Can a subclass directly access private members of its superclass?</h3>

<p>No. Private members cannot be accessed directly as ordinary inherited members. The subclass can use suitable public or protected methods provided by the superclass.</p>

<h3>Q14. What is the difference between inheritance and composition?</h3>

<p>Inheritance models an “is-a” relationship, while composition models a “has-a” relationship by using another object as a component.</p>

<h3>Q15. Why is the Object class important?</h3>

<p><code>Object</code> is the root superclass of Java classes and provides common methods such as <code>toString()</code>, <code>equals()</code>, and <code>hashCode()</code>.</p>

<h2>29. Quick Revision Checklist</h2>

<ul>

<li>Inheritance is a core concept of object-oriented programming.</li>

<li>The <code>extends</code> keyword establishes class inheritance.</li>

<li>A superclass provides common behavior; a subclass specializes it.</li>

<li>Java supports single, multilevel, and hierarchical class inheritance.</li>

<li>Java does not support extending multiple classes directly.</li>

<li>A class can implement multiple interfaces.</li>

<li>Constructors are not inherited, but superclass constructors can be invoked.</li>

<li>The <code>super</code> keyword refers to superclass constructors and accessible members.</li>

<li>Method overriding allows subclasses to specialize inherited instance methods.</li>

<li>Polymorphism allows superclass references to refer to subclass objects.</li>

<li>Private superclass members are not directly accessible in subclasses.</li>

<li>Use inheritance for “is-a” relationships and composition for “has-a” relationships.</li>

</ul>

<h2>30. Conclusion</h2>

<p>Inheritance is an essential feature of Java that helps developers build reusable, extensible, and logically organized object-oriented programs. By defining common functionality in a superclass and extending it through subclasses, developers can reduce duplication and represent relationships between related types.</p>

<p>Understanding the <code>extends</code> and <code>super</code> keywords, inheritance patterns, constructors, method overriding, and polymorphism provides a strong foundation for advanced Java topics. Always design inheritance hierarchies carefully and use composition when it provides a clearer and more flexible solution.</p>

<p>Continue learning with the <a href="https://www.justacademy.co/course-detail/core-java-training" target="_blank" rel="noopener noreferrer">JustAcademy Core Java Training Course</a>. You can also <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">register for a course demo</a> or visit the <a href="https://www.justacademy.co/" target="_blank" rel="noopener noreferrer">JustAcademy website</a> for more information.</p>

</div>

Previous Next
whatsapp